<template>
  <CDialog
    class="meter-dialog"
    :title="`${isEdit ? '编辑' : '新增'}仪表`"
    v-model:visible="dialogVisible"
    @confirm="handleConfirm"
    @cancel="dialogVisible = false"
    :loading="loading"
    size="small"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-position="top">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="仪表名称" prop="meterName">
            <el-input v-model="formData.meterName" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="仪表ID" prop="meterId">
            <el-input v-model="formData.meterId" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="仪表类型" prop="meterType">
            <CSelect v-model="formData.meterType" placeholder="请选择" clearable>
              <el-option
                v-for="item in TAAMeterTypeOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </CSelect>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="车间" prop="department">
            <CSelect v-model="formData.department" placeholder="请选择" clearable>
              <el-option
                v-for="item in departmentOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </CSelect>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="单位" prop="dataUnit">
            <CSelect v-model="formData.dataUnit" placeholder="请选择" clearable>
              <el-option
                v-for="item in unitOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </CSelect>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </CDialog>
</template>
<script lang="ts">
export default {
  name: 'MeterDialog'
};
</script>
<script lang="ts" setup>
import {
  defineProps,
  withDefaults,
  defineEmits,
  computed,
  ref,
  watch,
  reactive,
  onMounted
} from 'vue';
import { CDialog } from '@/components/CDialog';
import { CSelect } from '@/components/CSelect';
import { useMessage } from '@/hooks/useMessage';
import { getBase } from '@/apis/common/common';
import {
  getListDepartment,
  postDeviceAdd,
  postDeviceEdit
} from '@/apis/system/config/factoryWorkshopMeterSet';
import type { GetListDeviceResult } from '@/apis/system/config/model/factoryWorkshopMeterSetModel';
import { TAAMeterTypeEnum, TAAMeterTypeOption } from '@/constants/taa';
import { rules } from './rules';

interface MeterDialogProps {
  visible: boolean;
  plantNo: string;
  tempRow?: GetListDeviceResult;
}
const props = withDefaults(defineProps<MeterDialogProps>(), {
  visible: false
});
const emit = defineEmits(['update:visible', 'refresh']);
const { createMessage } = useMessage();
const dialogVisible = computed<boolean>({
  get: () => {
    return props.visible;
  },
  set: val => {
    emit('update:visible', val);
  }
});
watch(
  () => dialogVisible.value,
  visible => {
    if (!visible) {
      // 关闭时清空数据
      handleClear();
    } else {
      // 打开时初始化新数据
      initVisible();
    }
  }
);

const formRef = ref();
const loading = ref(false);
const formData = reactive({
  meterName: '',
  meterId: '',
  meterType: 'ELECTRIC' as keyof typeof TAAMeterTypeEnum,
  department: '',
  dataUnit: ''
});
const isEdit = computed(() => {
  return !!props.tempRow;
});

// 提交按钮
function handleConfirm() {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      submitTaskReq();
    }
  });
}

// 请求接口
async function submitTaskReq() {
  try {
    loading.value = true;
    const params = {
      ...formData,
      deviceNo: '',
      plantNo: ''
    };
    if (props.tempRow) {
      Object.assign(params, {
        deviceNo: props.tempRow.deviceNo
      });
      await postDeviceEdit(params);
    } else {
      Object.assign(params, {
        plantNo: props.plantNo
      });
      await postDeviceAdd(params);
    }
    createMessage.success(`${props.tempRow ? '编辑' : '新增'}仪表成功！`);
    dialogVisible.value = false;
    loading.value = false;
    emit('refresh');
  } catch (error) {
    loading.value = false;
  }
}

// 关闭时清空数据
function handleClear(clearData = true) {
  loading.value = false;
  formRef.value?.resetFields();
  if (clearData) {
    formData.meterId = '';
    formData.meterName = '';
    formData.meterType = 'ELECTRIC';
    formData.department = '';
    formData.dataUnit = '';
  }
}

// 打开时初始化
async function initVisible() {
  if (props.tempRow) {
    handleClear(false);
    formData.meterId = props.tempRow.meterId;
    formData.meterName = props.tempRow.meterName;
    formData.meterType = props.tempRow.meterType;
    formData.department = props.tempRow.department;
    formData.dataUnit = props.tempRow.dataUnit;
  } else {
    handleClear();
  }
}

/**
 * 获取车间 option
 */
// eslint-disable-next-line no-undef
const departmentOptions = ref<LabelValueOptions>([]);
async function getListDepartmentFn() {
  try {
    const res = await getListDepartment();
    departmentOptions.value =
      res?.map(item => {
        return {
          label: item,
          value: item
        };
      }) || [];
  } catch (error) {
    console.log('error', error);
    departmentOptions.value = [];
  }
}

// eslint-disable-next-line no-undef
const unitOptions = ref<LabelValueOptions>([]);
async function getUnitFn() {
  try {
    const res = await getBase('inventory:FACTOR_UNIT');
    unitOptions.value =
      res?.map(item => {
        return {
          label: item.dataCode,
          value: item.dataCode
        };
      }) || [];
  } catch (error) {
    console.log('error', error);
    departmentOptions.value = [];
  }
}

onMounted(() => {
  getListDepartmentFn();
  getUnitFn();
});
</script>
